package edu.ccut.saturn.studio.wfg.xml.loader;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;
import edu.ccut.saturn.studio.wfg.model.Shape;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnName;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnRouter;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnRouterNode;

public class SaturnRouterLoader extends NodeLoader {

	@Override
	public List<Shape> loadNodes(Element root) {
		NodeList routerNodes = root.getElementsByTagName(SaturnName.XML_NAME);
		List<Shape> routerList = new ArrayList<Shape>();
		
		for(int i = 0 ; i<routerNodes.getLength();i++){
			Node node = routerNodes.item(i);
			if(SaturnName.KEY_NONE_ATTIBUTRE_DECISION.equals(super.getNodeAttributeValue(node, SaturnName.XML_TYPE))){
				SaturnRouterNode saturnRouter = new SaturnRouterNode();
				saturnRouter.setId(super.getNodeAttributeValue(node, SaturnName.KEY_NODE_NAME_ID));
				saturnRouter.setName(super.getNodeElementValue(node, Shape.KEY_NODE_NAME));
				saturnRouter.setOffsetMode(super.getNodeElementValue(node, SaturnName.KEY_NODE_ELEMENT_OFFSETMODE));
				saturnRouter.setPolymeMode(super.getNodeElementValue(node, SaturnName.KEY_NODE_ELEMENT_POLYMEMODE));
				saturnRouter.setDescription(super.getNodeElementValue(node, Shape.KEY_NODE_DESCRIPTION));
				saturnRouter.setLocation(super.getLocation(node));
				saturnRouter.setNextId(super.getNodeAttributeValue(node, Shape.KEY_ATTRIBUTE_SHAPE_NEXT_ID));
				saturnRouter.setSize(super.getSize());
				
				List<SaturnRouter> list = saturnRouter.getRouterList();
				NodeList nodeList = node.getChildNodes();
				for(int k = 0 ;k<nodeList.getLength();k++){
					Node n = nodeList.item(k);
					if(n.getNodeName().equals(SaturnName.KEY_NODE_NAME_IF)){
						SaturnRouter saturn = new SaturnRouter();
						saturn.setId(SaturnW3CUtil.getNodeAttributeValue(n, SaturnName.KEY_NODE_NAME_THEN));
						saturn.setKey(SaturnW3CUtil.getChildNodeValue(n, SaturnName.KEY_NODE_NAME_EXPR));
						saturn.setLineName(SaturnW3CUtil.getChildNodeValue(n,SaturnName.KEY_NODE_NAME_LINENAME));
						list.add(saturn);
					}
				}
				saturnRouter.setRouterList(list);
				routerList.add(saturnRouter);
			}
		}
		
		return routerList;
	}
}
